# -*- coding: UTF-8 -*-
'''
@Project: stock
@File: StockCode.py
@Notes: 
@Author: zhuyoucheng
@Date: 2021/3/23 0023 18:31
'''

from App.Middleware.BaseMiddleware import BaseMiddleware
from App.Model.PyMysql import PyMysql
from App.Model.StockCodeModel import StockCodeModel
from App.Common.ElasticSearch import ElasticSearch
from App.Common.Function import Function
import baostock as bs
import pandas as pd
import datetime

class StockCode(BaseMiddleware):

    def save_stock_code(self, year=2021, month=4):

        type = 'shares'
        lg = bs.login()
        # 显示登陆返回信息
        print('login respond error_code:' + lg.error_code)
        print('login respond  error_msg:' + lg.error_msg)


        time = Function().getDays(year, month)
        if time:
            for day in time:
                date = "{year}-{month}-{day}".format(year=year, month=month, day=day)
                print(date)
                # 获取当前日期的所有股票的数据
                stock_rs = bs.query_all_stock(date)
                stock_df = stock_rs.get_data()
                res_data = []
                high = ''
                low = ''
                opens = ''
                close = ''
                now_date = ''
                if not stock_df.empty:
                    for code in stock_df["code"]:
                        try:
                            k_rs = bs.query_history_k_data_plus(code, "date,code,open,high,low,close", date, date)
                            data_df = k_rs.get_data()
                            high = data_df["high"][0]
                            low = data_df["low"][0]
                            opens = data_df["open"][0]
                            close = data_df["close"][0]
                            now_date = data_df["date"][0]
                            result = {"stock_code": code, 'type': 1, 'date': now_date, 'high': high, 'low': low, 'open': opens, 'close': close}
                            # 保存代码
                            print('--------------result--------------')
                            print(result)
                            # condition = {
                            #     'stock_code': code
                            # }
                            # res = StockCodeModel().getByCondition(condition,"*",1,1)
                            # if not res:
                            #     StockCodeModel().create(result)
                            # else:
                            #     StockCodeModel().update(condition, result)
                            #把股票数据刷进elasticSearch里
                            ElasticSearch().put(date, type, code, result)
                        except Exception as e:
                            print(e)


    def save_history_k_data(self, stock_code=''):

        pass
